package com.example.app13_sqlite.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.app13_sqlite.entity.BlackNumber;
import com.example.app13_sqlite.utils.DbHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * BlackNumberDao
 */
public class BlackNumberDao {

    private static final String TABLE_NAME = "black_number";

    private DbHelper dbHelper;

    public BlackNumberDao(Context context) {
        dbHelper = new DbHelper(context);
    }

    /**
     * 新增一条数据
     * @param blackNumber 实体
     */
    public void add(BlackNumber blackNumber) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        ContentValues values = new ContentValues();
        values.put("number", blackNumber.getNumber());
        long id = db.insert(TABLE_NAME, null, values);
        // 设置返回的ID
        blackNumber.setId(id);
        db.close();
    }

    /**
     * 根据id删除数据
     * @param id id
     */
    public void deleteById(Integer id) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        db.delete(TABLE_NAME, "_id=?", new String[] { id+"" });
        db.close();
    }

    /**
     * 更新数据
     * @param blackNumber 实体
     */
    public void update(BlackNumber blackNumber) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        ContentValues values = new ContentValues();
        values.put("number", blackNumber.getNumber());
        db.update(TABLE_NAME, values, "_id=?", new String[] { blackNumber.getId()+"" });
        db.close();
    }

    /**
     * 查询所有BlackNumber数据
     * @return 所有BlackNumber数据集合
     */
    public List<BlackNumber> getAll() {
        List<BlackNumber> list = new ArrayList<>(10);
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, "_id desc");
        while(cursor.moveToNext()) {
            list.add(new BlackNumber(cursor.getLong(0), cursor.getString(1)));
        }
        cursor.close();
        db.close();
        return list;
    }

}
